<template>
	<view class="">
	<view class="custom-navbar">
	  <view class="title" @click="goback"><u-icon name="arrow-left" color="black" size="50rpx"></u-icon></view>
	  <view class="reg-title" >
		  <view v-if="type == 1">
		  	<text v-if="status == 1">您已注册企业用户</text>
			<text v-else>企业用户注册信息</text>
		  </view>
		  
		  <text v-if="type == 2" >编辑个人信息</text>
	  </view>
	  <!-- 企业页面 -->
	  <view class="" v-if="type == 1">
		 
	  	 <view class="container">
	  	     <view  class="preview" @click="shouldChooseImage ? chooseImage() : null">
	  	       <image v-if="imageUrl" :src="imageUrl" mode="aspectFill"></image>
	  	 	  <view class="inner" v-else >
	  	 		  <view v-if="(status == 1)&&!imageUrl" class="innerif" style="color: white;background-color: #5ac725; width:600rpx;height: 300rpx;display: flex; align-items: center; justify-content: center;font-size: 50rpx;">
	  	 		  	<text>您已通过审核</text>
	  	 		  </view>
	  	 		  <view  v-else style="display: flex;flex-direction: column;">
	  	 		  	 <text>
	  	 		  						   点击上传营业执照
	  	 		  	 </text>
	  	 		  </view>
	  	 	  </view>
	  	     </view>
			 <view class="custominput">
			 	<u--input
			 		placeholder="企业名称"
			 		border="none"
			 		v-model="inputForm.entName"
			 				:disabled = "inptdis"
			 				disabledColor = white
			 	>
			 	</u--input>
			 </view>
			 <view class="custominput">
			 	<u--input
			 		placeholder="统一社会信用代码"
			 		border="none"
			 		v-model="inputForm.entNum"
			 				:disabled = "inptdis"
			 				disabledColor = white
			 	>
			 	</u--input>
			 </view>
			 <view class="custominput">
			 	<u--input
			 		placeholder="法人姓名"
			 		border="none"
			 		v-model="inputForm.legalName"
			 				:disabled = "inptdis"
			 				disabledColor = white
			 	>
			 	</u--input>
			 </view>
			 <view class="custominput">
			 	<u--input
			 		placeholder="法人身份证号"
			 		border="none"
			 		v-model="inputForm.legalNum"
			 				:disabled = "inptdis"
			 				disabledColor = white
			 	>
			 	</u--input>
			 </view>
			 
			
			 
	  	 	<view v-if="status == 0"  class="send-button" style="width: 80%;">
	  	 		<button  @click="showuploadImage? uploadImage() :null">{{showTips?"重新提交":"提交"}}</button>
	  	 	</view>
	  	 	<view v-if="status == 2"  style="width: 80%;display: flex;margin-top: 40rpx;">
	  	 		<u-button type="success">已提交</u-button>
	  	 		<u-button type="primary" @click="withdrawent">撤回</u-button>
	  	 	</view>
	  	 	<view v-if="status == 1"  style="width: 80%;display: flex;margin-top: 40rpx;">
	  	 		<u-button type="success" @click="goback">返回</u-button>
	  	 		<!-- <u-button  type="primary" @click="modifyent">修改企业</u-button> -->
	  	 	</view>
			<view v-if="showTips" style="width: 80%; margin: 20rpx auto;">
				您上传的图片不符合营业执照规范，请重新上传正确的营业执照，后续会有“天下工人”工作人员与您联系
			</view>
	  	 	<u-overlay :show="!showuploadImage">
	  	 			<view class="autloading" style="width: 100%;height: 100%;display: flex;justify-content: center;align-items: center;">
	  	 				<u-loading-icon :show="!showuploadImage" color="white"></u-loading-icon>
	  	 			</view>
	  	 	</u-overlay>
	  	   </view>
		   <!-- 环境 -->
		   <view v-if="status == 1" style="margin: 30rpx auto; width: 86%;background-color: skyblue;padding: 10rpx;border-radius: 20rpx;">
		   	<text>企业环境上传</text>
		   	<u-upload :fileList="entpiclist" @afterRead="afterRead" @delete="deletePic" name="1" multiple
		   		:maxCount="10" maxCount="8">
		   	</u-upload>
		   	<u-button v-if="showSubmitAddentpic" @click="SubmitAddentpic">提交</u-button>
		   </view>
	  </view>
	 <!-- 个人页面 -->
		<view class="" v-if="type == 2">
			<view class="custominput spbetween">
				<text style="display: block;margin-left: 15rpx;">姓名</text>
				<view style="display: flex;justify-content: flex-end;">
					<input type="text" v-model="FormData.nickName" style="text-align: right;"
						placeholder="请输入您的姓名" />
				</view>
			</view>
			<view class="custominput spbetween" style="margin-top: 30rpx;" @click="isshowsex=true">
				<text style="display: block;margin-left: 15rpx;">性别</text>
				<view style="display: flex;justify-content: flex-end;">
					<view style="display: flex;">
					<text style="margin-right: 15rpx;">{{FormData.gender?(FormData.gender==1?'男':'女'):'男'}}</text>
					<u-icon name="arrow-right" color="black" size="30rpx"></u-icon></view>
				</view>
			</view>
			<view class="custominput spbetween" style="margin-top: 30rpx;" @click="isshowmingzu=true">
				<text style="display: block;margin-left: 15rpx;">民族</text>
				<view style="display: flex;justify-content: flex-end;">
					<view style="display: flex;">
					<text style="margin-right: 15rpx;">{{mingzuList[mingzuIndex].name}}</text>
					<u-icon name="arrow-right" color="black" size="30rpx"></u-icon></view>
				</view>
			</view>
			<view class="custominput spbetween" style="margin-top: 30rpx;" @click="dateShow=true">
				<text style="display: block;margin-left: 15rpx;">出生日期</text>
				<view style="display: flex;justify-content: flex-end;">
					<view style="display: flex;">
					<text style="margin-right: 15rpx;">{{FormData.birthDate?FormData.birthDate:'请选择'}}</text>
					<u-icon name="arrow-right" color="black" size="30rpx"></u-icon></view>
				</view>
			</view>
			
			<view class="sub_btn">
				<u-button type="primary" text="提交" @click="commit" :disabled="!canclick"></u-button>
			</view>
			
			
		</view>
		<!-- 选项组件 -->
		<u-action-sheet style="border-radius: 10px;" :show="isshowsex" :actions="sexList" title="请选择性别"
			openType="launchApp" @select="sexSelect"  @close="isshowsex = false;" >
		</u-action-sheet>
		<u-picker :show="isshowmingzu" ref="mingzu" :columns="mingzuListcolumns" @confirm="mingzuConfirm"
			 @cancel="isshowmingzu = false"></u-picker>
		<u-datetime-picker
				:show="dateShow"
				v-model="dateVal"
				:minDate='-631152000000'
				:maxDate="maxDate"
				mode="date"
				@confirm="dateConfirm"
				@cancel="dateCancel"
				:formatter="formatter"
				></u-datetime-picker>
	</view>
	
	
	</view>
	
	
</template>

<script>
	//已注册企业详情
	import Index from "@/common/index-model.js"	
	import fun from '@/common/publicFun.js'
	let index = new Index()
	let that = null
	export default {
		data() {
			return {
				inptdis:false,//是否禁用输入框
				dateShow:false,
				dateVal:'2023-02-01',
				maxDate:'',
				type:'',
				imageUrl: '', // 用于预览图片的地址
				 tempFilePath: '', // 用于保存选择的图片文件路径
				 status:'',//审核状态
				 isEnterprising:'',//是否正在审核
				 hasEnterprise:'',//审核结果
				 shouldChooseImage:true,
				 showuploadImage:true,
				 inputForm:{
				 	id:'',
				 	clicense:'',
				 	entName:'',
				 	regNo:'',
				 	realName:'',
				 	idNo:'',
					hasAllPer:'',
					legalNum:'',
					legalName:'',
					entNum:''
				 },
				 
				 canclick:true,
				//
				mingzuIndex: 0, //默认选项				
				mingzuList: [],
				mingzuListcolumns: [],
				isshowsex: false,
				isshowmingzu: false,
				userinfo: {},
				sexList: [{
						name: '男',
						index: 1
					},
					{
						name: '女',
						index: 2
					}
				],
				FormData: {
					nickName: '',
					gender: 1,
					nation: 1,
					nationName: '',
					birthDate: '',
					avatar: '',
					provinceId: 0,
					cityId: 0,
					areaId: 0,
					degree: 0
				},
				showTips: false, //展示提示
				entpiclist: [], //企业图片
				showSubmitAddentpic:false,
			}
		},
		onLoad(e) {
			this.type = e.type
			if(e.type == 1){
				console.log("企业注册",e)
				if(e.data){
					let entdata = JSON.parse(e.data)
				this.imageUrl = entdata.clicense
				this.inputForm.clicense = entdata.clicense
				this.inputForm.entName = entdata.entName
				this.inputForm.legalName = entdata.realName
				this.inputForm.legalNum = entdata.idNo
				this.inputForm.entNum = entdata.regNo
				this.status = entdata.status
				if(this.status == 0){
					this.showTips = true
				}
				}
				
				// this.getPostInfo()
				// this.getState()
				// this.getentpiclist()
			}
			if(e.type == 2){
				console.log("个人注册",e.type)
				this.getNation()
				this.getUserInfo()
				let date=new Date();
				this.maxDate=date.getTime();
				this.dateVal=fun.formatDate(this.maxDate,"yyyy-MM-dd");
			}
			
		},
		methods: {
			//提交企业风采
			SubmitAddentpic(){
				
				if(this.inputForm.hasAllPer == 0){
					index.show_tips('您无权修改')
					return
				}
				
				let datalist = this.entpiclist.map(item => {return { url: item.url };})
				console.log(this.inputForm.id,datalist)
				index.getPublicUserMember({
					"enterpriseId": this.inputForm.id,
					"urlList": datalist
				}, '/etappearance/addAndupdate',
					'post', res => {
						if (res.data.code == 200 && res.data.success) {
							index.show_tips('提交成功，审核通过后可到入驻企业查看')
							this.showSubmitAddentpic = false
						} else {
							console.log(res)
						}
					})
			},
			// 删除图片
			deletePic(event) {
				this.entpiclist.splice(event.index, 1)
				this.showSubmitAddentpic = true
			},
			// 新增图片
			async afterRead(event) {
				this.showSubmitAddentpic = false
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = this.entpiclist.length
				lists.map((item) => {
					this.entpiclist.push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url)
					let item = this.entpiclist[fileListLen]
					this.entpiclist.splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url: result
					}))
					fileListLen++
				}
				console.log("上传的图片列表",this.entpiclist)
				this.showSubmitAddentpic = true
			},
			uploadFilePromise(url) {
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						url: index.img_url + 'client/public/upload?type=enterpriseAppearance&file=' + url,
						filePath: url,
						name: 'file',
						header: {
							'X-Access-Token': uni.getStorageSync('token'),
							'Login-Type': 'client'
						},
						success: (res) => {
							setTimeout(() => {
								resolve(JSON.parse(res.data).result.url)
							}, 1000)
						}
					});
				})
			},
			goback(){
				uni.navigateBack()
			},
		// 选择图片
			chooseImage() {
				uni.chooseImage({
				count: 1, // 最多选择一张图片
				sizeType: ['compressed'], // 压缩图片
				sourceType: ['album', 'camera'], // 选择图片的来源，相册或者相机
				success: (res) => {
					console.log("选择图片",res.tempFilePaths)
				this.showuploadImage = false
				this.tempFilePath = res.tempFilePaths;
				this.imageUrl = res.tempFilePaths[0]; // 显示选择的图片
					// 
					uni.uploadFile({
					  url: index.img_url + 'client/public/upload?type=enterpriseLicense&file=' + this.tempFilePath,
					  filePath: this.tempFilePath[0],
					  name: 'file',
					  formData: {
					    // 可以添加额外的表单数据
					  },
								header: {
									'X-Access-Token': uni.getStorageSync('token'),
									'Login-Type': 'client'
								},
					  success: (res) => {
									if(res.statusCode === 200){
										let imgurl = JSON.parse(res.data).result.url
										this.inputForm.clicense = imgurl
										index.getPublicUserMember({licenseUrl:imgurl},'/client/realauth/enterpriseByOCR','get',res=>{
											if(res.data.code == 200 && res.data.success){
												this.showuploadImage = true
												console.log("营业执照信息",res)
												this.inputForm.entName = res.data.result.companyName
												this.inputForm.entNum = res.data.result.creditCode
												this.inputForm.legalName = res.data.result.legalPerson
											}else{
												this.showuploadImage = true
												index.show_tips(res.data.message);
															console.log(res.data.message)
											}
										})
									}else{
										 if (res.statusCode === 413) {
											 this.showuploadImage = true
										            index.show_tips('文件过大，请重新上传');
										        } else {
										            index.show_tips('服务器返回错误，请稍后再试');
										        }
									}
									
					  },
					  fail: (err) => {
									index.show_tips('上传失败,请重新上传营业执照')
									 this.showuploadImage = true
									 this.inptdis = false
					    // 上传失败的处理逻辑
					    console.error('上传失败,请重新上传营业执照', err);
					  }
					})
					// 
					}
				});
			},
		// 上传图片
		uploadImage() {
			if(!this.inputForm.entName){
				index.show_tips('请填写企业名称')
				return
			}
			if(!this.imageUrl){
				index.show_tips('请上传营业执照')
				return
			}
			
			index.show_tips('上传中')
			console.log("上传了图片",this.tempFilePath)
			if (!this.tempFilePath) {
				index.show_tips('请重新上传营业执照')
				return
			}
			this.showTips = false
			this.showuploadImage = false
		  // 这里可以添加上传图片的逻辑，上传到服务器等
		  // if(this.isEnterprising == 0||this.status == 0){
		  				 this.subent()
		  // }else{
		  // 				 console.log('reAuthEnterprise')
		  // 				 index.getPublicUserMember(this.inputForm,'/client/realauth/reAuthEnterprise','post',res=>{
		  // 				 	if(res.data.code == 200 && res.data.success){
		  // 				 		index.show_tips('已提交，等待审核')
		  // 				 					this.getPostInfo()
		  // 				 					this.getState()
		  // 				 					this.shouldChooseImage = false
		  // 				 	}else{
		  // 				 		index.show_tips(res.data.message);
		  // 				 					console.log(res.data.message)
		  // 				 		return false
		  // 				 	}
		  // 				 })
		  // }
		},
		//提交企业
		subent(){
			index.getPublicUserMember({
				clicense:this.inputForm.clicense,
				entName:this.inputForm.entName,
				idNo:this.inputForm.legalNum,
				regNo:this.inputForm.entNum,
				realName:this.inputForm.legalName
			},'/client/realauth/submitEnterpriseNew','post',res=>{
				if(res.data.code == 200 && res.data.success){
					this.showuploadImage = true
					index.show_tips('已提交，等待审核')
								// this.getPostInfo()
								// this.getState()
								this.shouldChooseImage = false
								 setTimeout(() => {
								      uni.navigateBack()
								      }, 1000);
				}else{
					this.showuploadImage = true
					index.show_tips(res.data.message);
								console.log(res.data.message)
					return false
				}
			})
		},
		//撤回审核
		withdrawent(){	
			uni.showModal({
			        title: '确认撤回',
			        content: '您确定要撤回审核吗？',
			        success: (res) => {
			          if (res.confirm) {
			            console.log('用户点击确定');
			           index.getPublicUserMember({},'/client/enterprise/info/delEnterprise/'+this.inputForm.id,'put',res=>{
			           	console.log(res)
			           	// this.getPostInfo()
			           	// this.getState()
			           	// this.inputForm.entName = ''
			           	// this.inptdis = false
			           	// this.shouldChooseImage = true
			           	// this.imageUrl = ""
			           	if(res.data.code == 200){
			           		setTimeout(() =>{
			           			this.goback()
			           		},1000)
			           		index.show_tips('已撤回')
			           	}
			           	else{
			           		index.show_tips('撤回失败')
			           	}
			           	
			           })
			          } else if (res.cancel) {
			            console.log('用户点击取消');
			          }
			        }
			      });
			
		},
		//修改审核
		modifyent(){
			uni.showModal({
			        title: '确认修改',
			        content: '您确定要修改企业认证吗？（修改时需重新提交营业执照）',
			        success: (res) => {
			          if (res.confirm) {
			            console.log('用户点击确定');
						this.inputForm.clicense = this.imageUrl
						this.uploadImage()
						
			          } else if (res.cancel) {
			            console.log('用户点击取消');
			          }
			        }
			      });
		},
		// 获取上传状态
		// getState() {
		// 	index.getPublicUserMember({},'/client/enterprise/info/enterpriseStatus','get',res=>{
		// 		console.log(res.data.result)
		// 		this.status = res.data.result.status
		// 		this.isEnterprising = res.data.result.isEnterprising
		// 		this.hasEnterprise = res.data.result.hasEnterprise
		// 		if(res.data.result.status==2&&res.data.result.isEnterprising == 1){
		// 			this.inptdis = true
		// 		}
		// 		// if(res.data.result.status==1||res.data.result.hasEnterprise == 1){
		// 		// 	this.inptdis = true
		// 		// }
		// 		if(res.data.result.status == 0){
		// 			index.show_tips('认证失败,请重新上传')
		// 			this.showTips = true
		// 			this.inputForm.entName = ''
		// 			this.inptdis = false
		// 			this.shouldChooseImage = true
		// 			this.imageUrl =""
		// 		}
				
		// 	})
		// },
		//获取企业所上传图片
		getentpiclist(){
			let url = '/etappearance/list/'+this.inputForm.id
			console.log("这是url",url)
			index.getPublicUserMember({},'/etappearance/listAll/'+this.inputForm.id,'get',res=>{
				if(res.data.code == 200 && res.data.success){
					console.log("请求图片数据->",res)
					this.entpiclist = res.data.result.map(item => {return { url: item.url };})
					
				}else{
					console.log("请求失败",res) 
		
				}
			})
		},
		//查看企业详情
		// getPostInfo() {
		// 	index.getPublicUserMember({},'/client/enterprise/info/detailNew','get',res=>{
		// 		console.log(res.data.result,"结果")
		// 		if(res.data.result){
		// 			if(res.data.result.status != 0){
		// 			this.shouldChooseImage = false
		// 			this.imageUrl = res.data.result.clicense
		// 		}
		// 		if(res.data.result.status == 1){
		// 			this.shouldChooseImage = true
		// 			this.imageUrl = res.data.result.clicense
		// 		}
		// 		if(res.data.result.cname){
		// 			this.inputForm.entName = res.data.result.cname
		// 		}
		// 		if(res.data.result.entName){
		// 			this.inputForm.entName = res.data.result.entName
		// 		}
		// 		if (res.data.result.id) {
		// 			this.inputForm.id = res.data.result.id
		// 			this.getentpiclist()
		// 		}
		// 		if (res.data.result.hasAllPer) {
		// 			this.inputForm.hasAllPer = res.data.result.hasAllPer
		// 		}
		// 		}
				
				
		// 	})
		// },
		//选择民族
		mingzuConfirm(e) {
			this.isshowmingzu = false
			this.mingzuIndex = e.indexs[0]
			this.FormData.nation = this.mingzuList[this.mingzuIndex].id
		},
		//选择性别
		sexSelect(e) {
			console.log(e, '--性别--')
			this.FormData.gender = e.data.index
		},
		//选择日期
		dateConfirm(e){
			this.FormData.birthDate = fun.timestampToTime(e.value, '-');
				console.log('选择的日期是', this.FormData.birthDate)
				this.dateShow = false;
		},
		dateCancel(e){
			this.dateShow=false;
		},
		//获取民族信息
		getNation() {
			index.getPublicUserMember({}, 'client/public/find/nationList', 'get', res => {
				console.log("获取名族信息", res)
				this.mingzuList = res.data.result
				// if (this.mingzuList.length > 0) {
				// 	this.mingzuIndex = 0
				// 	this.FormData.nation = this.mingzuList[0].id
				// }
				let arr = []
				for (let k = 0; k < this.mingzuList.length; k++) {
					arr[k] = this.mingzuList[k].name
				}
				console.log("获取名族信息", arr)
				this.mingzuListcolumns.push(arr)
		
			})
		},
		//获取用户信息
		getUserInfo() {
			index.getPublicUserMember({
				"uid": uni.getStorageSync('userid')
			}, '/client/card/detailNoAudit', 'get', res => {
				this.userinfo = res.data.result;
				console.log('获取的个人信息是', this.userinfo)
				if(res.data.result.nation){
					this.mingzuIndex = res.data.result.nation - 1
					this.FormData.nation = res.data.result.nation
				}else{
					this.mingzuIndex = 0
					this.FormData.nation = 1
				}
				this.FormData.nickName = res.data.result.nickName
				this.FormData.gender = res.data.result.gender
				this.FormData.birthDate = res.data.result.birthDate
			})
		},
		//提交
		commit() {
			uni.showLoading({
				title: '请稍后。。。',
			})
			if (!this.FormData.nickName) {
				index.show_tips('请输入您的姓名');
				return false;
			}
			if (!this.FormData.birthDate) {
				index.show_tips('请选择您的生日');
				return false;
			}
			let sends = {
				"nickName": this.FormData.nickName,
				"gender": this.FormData.gender,
				"nation": this.FormData.nation,
				"birthDate": this.FormData.birthDate,
				"mobile": this.FormData.mobile,
				"avatar": this.FormData.avatar,
				"provinceId": this.FormData.provinceId,
				"cityId": this.FormData.cityId,
				"areaId": this.FormData.areaId,
				"degree":this.FormData.degree
			}
			console.log('提交的信息是', sends)
			index.getPublicUserMember(sends, 'client/individual/information', 'post', res => {
				if (res.data.code == 200 && res.data.success) {
					index.show_tips('个人信息修改成功')
					this.canclick = false
					setTimeout(() => {
						uni.navigateBack();
					}, 1000)
				} else {
					index.show_tips(res.data.message);
					return false
				}
			})
		}
		
	}
	}
</script>
<style>
	page{
		background: #f3f3f3;
	}
</style>
<style scoped>
	@import url("@/static/css/publics.css");
	@import url("@/static/css/myeditphone.css");
.custom-navbar{
	height: 26vh;
	width: 100%;
	background: linear-gradient(180deg, #8DC0FF 0%, rgba(255, 255, 255, 0) 100%);
}
.title{
	padding-top: 100rpx;
	margin-left: 40rpx;
}
.reg-title{
	color: #000000;display: flex; 
	align-items: end;
	justify-content: center;
	margin-top: 50rpx;
	font-size: 48rpx;
	font-weight: bold;
}
.entclaim {
		margin: 0 auto;
		width: 90%;
		border-radius: 14rpx;
		box-shadow: 0px 2px 4px -2px rgba(0, 0, 0, 0.1), 0px 4px 6px -1px rgba(0, 0, 0, 0.1);
		padding: 30rpx;
		box-sizing: border-box;
		display: flex;
		justify-content: space-between;
		align-items: center;
	}
.custominput{
	width: 80%;
	height: 88rpx;
	background-color: #fff;
	margin: 0 auto;
	margin-top: 20rpx;
	border-radius: 10rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	padding: 0 10rpx;
	box-sizing: border-box;
}
.preview {
	margin-top:40rpx ;
	  border-radius: 10rpx;
	  height: 300rpx;
	  width: 80%;
	  display: flex;
	  align-items: center;
	  justify-content: center;
	  text-align: center;
	  background-color: #fff;
	  border: 0;
	  overflow: hidden;
	  box-sizing: border-box;
	}
	.sub_btn{
		width: 80%;
		margin: 0 auto;
		margin-top: 48rpx;
		/* padding: 0 50rpx ; */
		box-sizing: border-box;
	}
	.spbetween{
		display: flex;justify-content: space-between;
	}
</style>
